<?php

namespace App\Http\Controllers\Api;

use App\Lib\JwtAuth;
use App\Models\WxChat;
use App\Models\WxNotice;
use App\Models\WxUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;


class MessagesController extends BaseController
{

    /**
     * 消息页数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMessages(Request $request)
    {

        $uid = $request->uid;

        $noticeSystemCount = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [0, 1, 7, 8])
            ->count();
        $noticeSystem = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [0, 1, 7, 8])
            ->orderByRaw('created_at DESC')
            ->first(['created_at', 'title']);
        $noticeSystemText = '还没有新通知';
        if ($noticeSystemCount > 0) {
            $noticeSystemText = $noticeSystem['title'];
        }

        $noticeLikeCollectCount = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [2, 3, 5])
            ->count();
        $noticeLikeCollect = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [2, 3, 5])
            ->orderByRaw('created_at DESC')
            ->first(['created_at', 'title']);
        $noticeLikeCollectText = '还没有新的赞和收藏';
        if ($noticeLikeCollectCount > 0) {
            $noticeLikeCollectText = $noticeLikeCollect['title'];
        }

        $noticeCommentCount = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [4, 6])
            ->count();
        $noticeComment = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [4, 6])
            ->orderByRaw('created_at DESC')
            ->first(['created_at', 'title']);
        $noticeCommentText = '还没有新的评论和打赏';
        if ($noticeCommentCount > 0) {
            $noticeCommentText = $noticeComment['title'];
        }

        $list = [
            ['noticeSystemText' => $noticeSystemText, 'noticeSystemCount' => $noticeSystemCount, 'noticeSystemDate' => format_datetime($noticeSystem['created_at'])],
            ['noticeLikeCollectText' => $noticeLikeCollectText, 'noticeLikeCollectCount' => $noticeLikeCollectCount, 'noticeLikeCollectDate' => format_datetime($noticeLikeCollect['created_at'])],
            ['noticeCommentText' => $noticeCommentText, 'noticeCommentCount' => $noticeCommentCount, 'noticeCommentDate' => format_datetime($noticeComment['created_at'])]
        ];

        return $this->success($list);
    }

    /**
     * 通知详情页数据
     * @param Request $request
     * 系统通知：0，1, 7, 8
     * 赞和收藏通知：2，3，5
     * 评论和打赏通知：4，6
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDetailsMessages(Request $request)
    {

        $uid = $request->uid;
        $type = $request->type;
        if ($type == 0) {
            $list = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [0, 1, 7, 8])
                ->orderByRaw('created_at DESC')
                ->paginate(10);
        } else if ($type == 1) {
            $list = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [2, 3, 5])
                ->orderByRaw('created_at DESC')
                ->paginate(10);
        } else if ($type == 2) {
            $list = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [4, 6])
                ->orderByRaw('created_at DESC')
                ->paginate(10);
        }

        $list->map(function ($v)use($type) {
            if($type == 0){
                $v->qh_image = '/image/qinghang-message.png';
            } else if ($type == 1) {
                $v->qh_image = '/image/like-message.png';
            } else if ($type == 2) {
                $v->qh_image = '/image/comments-message.png';
            }
            return $v;
        });

        return $this->success($list);
    }

    /**
     * 已读对应类通知
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readMessages(Request $request)
    {

        $uid = $request->uid;
        $type = $request->type;
        if ($type == 0) {
            $notice = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [0, 1, 7, 8])
                ->update(['is_read' => 1]);
            return $this->success($notice);
        } else if ($type == 1) {
            $notice = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [2, 3, 5])
                ->update(['is_read' => 1]);
            return $this->success($notice);
        } else if ($type == 2) {
            $notice = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [4, 6])
                ->update(['is_read' => 1]);
            return $this->success($notice);
        }
    }

    /**
     * 查询用户聊天记录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserChatList(Request $request)
    {

        $uid = $request->uid;

        $data = WxChat::where(function ($query) use ($uid) {
            $query->where('user_id', $uid)
                ->orWhere('object_id', $uid);
        })
            ->where('chat_state', 0)
            ->orderBy('id', 'desc')
//            ->groupBy('object_id')
            ->get()->toArray();

        //  二维数组去重
        $res = array();
        foreach ($data as $value) {
            if (!empty($value['object_id']) && $value['object_id'] != $uid) {
                if (!isset($res[$value['object_id']])) {
                    $res[$value['object_id']] = $value;

                    $res[$value['object_id']]['datetime'] = format_datetime($value['created_at']);

                    $res[$value['object_id']]['read'] =
                        WxChat::where('user_id', $value['object_id'])
                            ->where('is_read', 0)
                            ->where('object_id', $uid)
                            ->orderBy('id', 'desc')
                            ->first();

                    $res[$value['object_id']]['user'] =
                        WxUser::where('id', $value['object_id'])
                            ->first();


                    $res[$value['object_id']]['read_count'] =
                        WxChat::where('object_id', $uid)
                            ->where('user_id', $value['object_id'])
                            ->where('is_read', 0)
                            ->count();

                }
            } else if (!empty($value['user_id'] && $value['object_id'] == $uid)) {
                if (!isset($res[$value['user_id']])) {
                    $res[$value['user_id']] = $value;

                    $res[$value['user_id']]['datetime'] = format_datetime($value['created_at']);

                    $res[$value['user_id']]['read'] =
                        WxChat::where('user_id', $value['object_id'])
                            ->where('is_read', 0)
                            ->where('object_id', $uid)
                            ->orderBy('id', 'desc')
                            ->first();

                    $res[$value['user_id']]['user'] =
                        WxUser::where('id', $value['user_id'])
                            ->first();

                    $res[$value['user_id']]['read_count'] =
                        WxChat::where('object_id', $uid)
                            ->where('user_id', '!=', $uid)
                            ->where('is_read', 0)
                            ->count();

                }
            }
        }

        return $this->success(array_merge($res));
    }


    /**
     * 查询用户是否有未读信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSysMessageCount(Request $request)
    {
        $count = 0;
        $token = $request->header('token');
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
            $noticeCount = WxNotice::where('user_id', $uid)
                ->where('is_read', 0)
                ->count();

            $chatCount = WxChat::where('object_id', $uid)
                ->where('user_id', '!=', $uid)
                ->where('is_read', 0)
                ->count();

            $count = $noticeCount + $chatCount;
        }
        return $this->success($count);
    }


}
